<!DOCTYPE html>












  




<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <!-- hexo-inject:begin --><!-- hexo-inject:end --><meta charset="UTF-8"/>
<meta name="google-site-verification" content="o9IkI77-fxkhBZW-n0ww9JALMCqdDbeTgdcXO_Bw4Zc" />
<meta name="baidu-site-verification" content="3frqY9KiVO" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">



  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">










<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



















  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.4.1" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/logo.png?v=6.4.1">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/logo.png?v=6.4.1">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/logo.png?v=6.4.1">


  <link rel="mask-icon" href="/images/logo.svg?v=6.4.1" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.4.1',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="摘要：Python作为一门简洁优美且功能强大的语言，越来越受编程人员的喜欢。在工业界和学术界也是非常受欢迎的编程语言。python语言可以跨平台跨应用开发。本系列文章首先介绍Python语言及其可以做什么事情。哪些人群适合学习python和python语法特点。其次介绍了Python进阶，以实际案例演示常用的语句和控制流、表达式、函数、数据结构、标准库等知识点。然后扩展介绍了python第三方库">
<meta name="keywords" content="Python">
<meta property="og:type" content="article">
<meta property="og:title" content="简明的Python教程之实例篇">
<meta property="og:url" content="https://bainingchao.github.io/2018/10/10/简明的Python教程之实例篇/index.html">
<meta property="og:site_name" content="白宁超的官网">
<meta property="og:description" content="摘要：Python作为一门简洁优美且功能强大的语言，越来越受编程人员的喜欢。在工业界和学术界也是非常受欢迎的编程语言。python语言可以跨平台跨应用开发。本系列文章首先介绍Python语言及其可以做什么事情。哪些人群适合学习python和python语法特点。其次介绍了Python进阶，以实际案例演示常用的语句和控制流、表达式、函数、数据结构、标准库等知识点。然后扩展介绍了python第三方库">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://pub.idqqimg.com/wpa/images/group.png">
<meta property="og:updated_time" content="2019-03-06T08:56:49.434Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="简明的Python教程之实例篇">
<meta name="twitter:description" content="摘要：Python作为一门简洁优美且功能强大的语言，越来越受编程人员的喜欢。在工业界和学术界也是非常受欢迎的编程语言。python语言可以跨平台跨应用开发。本系列文章首先介绍Python语言及其可以做什么事情。哪些人群适合学习python和python语法特点。其次介绍了Python进阶，以实际案例演示常用的语句和控制流、表达式、函数、数据结构、标准库等知识点。然后扩展介绍了python第三方库">
<meta name="twitter:image" content="http://pub.idqqimg.com/wpa/images/group.png">



  <link rel="alternate" href="/atom.xml" title="白宁超的官网" type="application/atom+xml" />




  <link rel="canonical" href="https://bainingchao.github.io/2018/10/10/简明的Python教程之实例篇/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>简明的Python教程之实例篇 | 白宁超的官网</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript><!-- hexo-inject:begin --><!-- hexo-inject:end -->

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <!-- hexo-inject:begin --><!-- hexo-inject:end --><div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

	<!-- <a href="https://github.com/bainingchao"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png" alt="Fork me on GitHub"></a> !-->
	
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">白宁超的官网</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">专注人工智能领域研究</h1>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-首页">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-标签">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-分类">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-归档">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-视频">
    <a href="/videos/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br />视频</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-书籍">
    <a href="/books/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />书籍</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-链接">
    <a href="/links/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />链接</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-关于">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://bainingchao.github.io/2018/10/10/简明的Python教程之实例篇/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="白宁超">
      <meta itemprop="description" content="本站主要研究深度学习、机器学习、自然语言处理等前沿技术。ML&NLP交流群：436303759 <span><a target="_blank" href="http://shang.qq.com/wpa/qunwpa?idkey=ef3bbb679b06ac59b136c57ba9e7935ff9d3b10faeabde6e4efcafe523bbbf4d"><img border="0" src="http://pub.idqqimg.com/wpa/images/group.png" alt="自然语言处理和机器学习技术QQ交流：436303759 " title="自然语言处理和机器学习技术交流"></a></span>">
      <meta itemprop="image" content="/../images/header.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="白宁超的官网">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">简明的Python教程之实例篇
              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-10-10 09:45:14" itemprop="dateCreated datePublished" datetime="2018-10-10T09:45:14+08:00">2018-10-10</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-03-06 16:56:49" itemprop="dateModified" datetime="2019-03-06T16:56:49+08:00">2019-03-06</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/Python/" itemprop="url" rel="index"><span itemprop="name">Python</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon"
            >
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          
		  

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p>摘要：Python作为一门简洁优美且功能强大的语言，越来越受编程人员的喜欢。在工业界和学术界也是非常受欢迎的编程语言。python语言可以跨平台跨应用开发。本系列文章首先介绍Python语言及其可以做什么事情。哪些人群适合学习python和python语法特点。其次介绍了Python进阶，以实际案例演示常用的语句和控制流、表达式、函数、数据结构、标准库等知识点。然后扩展介绍了python第三方库，使读者对python有个全面的理解和认识。最后一节，采用实际案例帮助读者综合运用python知识。 （本文原创，转载必须注明出处.）</p>
</blockquote>
<a id="more"></a>
<h1 id="语句和控制流"><a href="#语句和控制流" class="headerlink" title="语句和控制流"></a>语句和控制流</h1><h2 id="Hello-World"><a href="#Hello-World" class="headerlink" title="Hello World"></a>Hello World</h2><p>编程第一步，打印“Hello World”的输入结果：</p>
<pre>
def callHello():
    print("hello world！")

callHello()
</pre>

<p>运行结果：</p>
<pre><code>hello world！
</code></pre><h2 id="if-语句-根据成绩评判等级"><a href="#if-语句-根据成绩评判等级" class="headerlink" title="if 语句::根据成绩评判等级"></a>if 语句::根据成绩评判等级</h2><pre>
# if 语句:根据成绩评判等级
def CallLevel(score):
    if score >= 90 :
        print("优秀")
    elif score >= 60:
        print("及格")
    else:
        print("不及格")
CallLevel(score=60)
</pre>
运行结果：

    及格

## for 语句:循环输出所有评分指标

    # for 语句:循环输出所有评分指标
    def GetLevel(score):
        for lev in score:
            print(lev,end=" ") # 设置不换行
    GetLevel(score=["优秀","及格","不及格"]) # 列表参数

运行结果：

    优秀 及格 不及格

## while 语句:循环输出所有评分
<pre>
# while 语句:循环输出所有评分
def GetLevel2(score):
    countlen=len(score)
    while countlen > 0:
        print(score[countlen-1],end=" ") # 设置不换行
        countlen -= 1

GetLevel2(score=[90,30,100,98,60])
</pre>
运行结果：

    60 98 100 30 90 

> range() 函数:循环输出所有评分指标的下标
<pre>
# range() 函数:循环输出所有评分指标的下标
def GetValue(score):
    for lev in range(len(score)):
        print(lev,end=" ")
GetValue(score=["优秀","及格","不及格"])
</pre>
运行结果：

    0 1 2 

## break 语句：统计优秀学生的个数
<pre>
# break 语句:不及格的跳过
def GetHighLev(score):
    result=0
    for lev in score:
        if lev < 90:
            break
        else:
            result += 1
    print("成绩优秀的学生有："+str(result)+"位。")

GetHighLev(score=[90,30,100,98,60])
</pre>
运行结果：

    成绩优秀的学生有：1位。

    分析：实际优秀者个数是90,100,98共计3位，输出结果却是1位。造成这种结果的原因是，当循环输入列表90时候，满足条件自动加1.继续输入30，不满足条件，直接跳出整个程序，输出最后一条语句。



## continue 语句：统计优秀成绩的个数
<pre>
# continue 语句:统计优秀成绩的个数
def GetHighLev2(score):
    result=0
    for lev in score:
        if lev < 90:
            continue
        else:
            result += 1
    print("成绩优秀的学生有："+str(result)+"位。")

GetHighLev2(score=[90,30,100,98,60])
</pre>
运行结果：

    成绩优秀的学生有：3位。

> pass 语句：什么也不做，占位符
<pre>
# pass 语句：什么也不做，占位符
def callPass():
    pass
print(callPass())
</pre>
运行结果：

    None


***
# 函数
## 定义函数：斐波那契数列
<pre>
# 输出指定数的斐波那契数列
def fib(n):
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a+b
    print()
fib(100)
</pre>
运行结果：

     0 1 1 2 3 5 8 13 21 34 55 89 
结果分析：

关键字 def 引入了一个函数定义。在其后必须跟有函数名和包括形式参数的圆括号。函数体语句从下一行开始，必须是缩进的。一个函数定义会在当前符号表内引入函数名。函数名指代的值（即函数体）有一个被 Python 解释器认定为用户自定义函数的类型。

## 函数默认参数
<pre>
# 函数默认参数
def sayhello(name="Tom"):
    print("Hello,"+name)

sayhello()
</pre>
运行结果：

    Hello,Tom

## 关键字参数
<pre>
# 关键字参数
def person(name, age, **kw):  #前两个是必须参数，最后一个可选可变参数
    print('name:', name, 'age:', age, 'other:', kw)

person("Tome",30) # 只调用必须参数
person("Tom",30,city="ChengDu",sex="man") # 自定义关键字参数
</pre>
运行结果：

    name: Tome age: 30 other: {}
    name: Tom age: 30 other: {'sex': 'man', 'city': 'ChengDu'}

## 可变参数
<pre>
# 可变参数
def concat(*args, sep="/"):
    print(sep.join(args))
concat('我','是','可变','参数')
</pre>
运行结果：

    我/是/可变/参数

## Lambda 形式
<pre>
# Lambda 形式
def Lambda(nums):
    nums.sort(key=lambda num: num[0])
    print(nums)

Lambda(nums = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')])
</pre>
运行结果：

    [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]


***

# List 列表
## list常用方法
<pre>
list.append(x)    添加元素到列表尾部。
list.extend(L)    列表合并。
list.insert(i, x) 在指定位置插入一个元素。
list.remove(x)    删除列表中值为 x 的第一个元素。
list.pop([i])     从列表的指定位置删除元素，并将其返回。
list.clear()      从列表中删除所有元素。相当于 del a[:]。
list.index(x)     返回列表中第一个值为 x 的元素的索引。
list.count(x)     返回 x 在列表中出现的次数。
list.sort()       对列表中的元素就地进行排序。
list.reverse()    就地倒排列表中的元素。
list.copy()       返回列表的一个浅拷贝。等同于 a[:]。
</pre>

<h2 id="列表的切分"><a href="#列表的切分" class="headerlink" title="列表的切分"></a>列表的切分</h2><pre>
# 列表的切分
def calllist(names):
    print(names[-1:]) # 输出列表最后一个值
    print(names[:3])  # 输出列表前3个值
calllist(names=['this','is','a','list'])
</pre>

<p>运行结果：</p>
<pre><code>[&#39;list&#39;] 
[&#39;this&#39;, &#39;is&#39;, &#39;a&#39;]
</code></pre><h2 id="List-列表作堆栈-先进先出"><a href="#List-列表作堆栈-先进先出" class="headerlink" title="List :列表作堆栈(先进先出)"></a>List :列表作堆栈(先进先出)</h2><pre>
# 把列表当作堆栈使用
def SomeList(stack):
    print("原始列表（栈）：",end=' ')
    print(stack)
    stack.append('贺知章')
    stack.append('杜牧')
    print("追加后列表（栈）：",end=' ')
    print(stack)
    stack.pop()
    stack.pop()
    print("出栈后的数据：",end=' ')
    print(stack)

SomeList(stack=['李白','杜甫', '白居易'])
</pre>

<p>运行结果：(先进先出)</p>
<pre><code>原始列表（栈）： [&#39;李白&#39;, &#39;杜甫&#39;, &#39;白居易&#39;]
追加后列表（栈）： [&#39;李白&#39;, &#39;杜甫&#39;, &#39;白居易&#39;, &#39;贺知章&#39;, &#39;杜牧&#39;]
出栈后的数据： [&#39;李白&#39;, &#39;杜甫&#39;, &#39;白居易&#39;]
</code></pre><h2 id="List-列表作队列-先进后出"><a href="#List-列表作队列-先进后出" class="headerlink" title="List :列表作队列(先进后出)"></a>List :列表作队列(先进后出)</h2><pre>
# 把列表当作队列使用：使用队列时调用collections.deque，它为在首尾两端快速插入和删除而设计。
from collections import deque
def SomeList2(queue):
    print("原始列表：",end=' ')
    print(queue)
    queue.append("李商隐")
    queue.append("杜牧")
    print("入队的列表：",end=' ')
    print(queue)
    queue.popleft()
    queue.popleft()
    print("出队后列表：",end=' ')
    print(queue)

SomeList2(queue = deque(['李白','杜甫', '白居易']))
</pre>

<p>运行结果：(先进后出)</p>
<pre><code>原始列表： deque([&#39;李白&#39;, &#39;杜甫&#39;, &#39;白居易&#39;])
入队的列表： deque([&#39;李白&#39;, &#39;杜甫&#39;, &#39;白居易&#39;, &#39;李商隐&#39;, &#39;杜牧&#39;])
出队后列表： deque([&#39;白居易&#39;, &#39;李商隐&#39;, &#39;杜牧&#39;])
</code></pre><h2 id="列表推导式"><a href="#列表推导式" class="headerlink" title="列表推导式"></a>列表推导式</h2><pre>
# 列表推导式
def callList(nums):
    squares = [n**2 for n in nums]
    print(squares)
callList(nums=[2,4,6,8])
</pre>

<p>运行结果：</p>
<pre><code>[4, 16, 36, 64]
</code></pre><h2 id="列表的矩阵转秩"><a href="#列表的矩阵转秩" class="headerlink" title="列表的矩阵转秩"></a>列表的矩阵转秩</h2><pre>
# 矩阵转秩
def countList(matrix):
    result = [[row[i] for row in matrix] for i in range(4)]
    print(result)

matrix = [
     [1, 2, 3, 4],
     [5, 6, 7, 8],
     [9, 10, 11, 12],
]
countList(matrix)
</pre>

<p>运行结果：</p>
<pre><code>[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
</code></pre><hr>
<h1 id="元组-集合-字典"><a href="#元组-集合-字典" class="headerlink" title="元组/集合/字典"></a>元组/集合/字典</h1><p>虽然元组和列表很类似，它们经常被用来在不同的情况和不同的用途。元组有很多用途。例如 (x, y) 坐标对，数据库中的员工记录等等。元组就像字符串， 不可变的。列表是可变的 ，它们的元素通常是相同类型的并通过迭代访问。</p>
<h2 id="操作元组"><a href="#操作元组" class="headerlink" title="操作元组"></a>操作元组</h2><pre>
def calltuple(tuples):
    for t in tuples:
        print(t+"\t",end=" ")
    print()
calltuple(tuples=('百度','阿里巴巴','腾讯')) # 元组参数
</pre>

<p>运行结果：</p>
<pre><code>百度     阿里巴巴     腾讯    
</code></pre><h2 id="set集合"><a href="#set集合" class="headerlink" title="set集合"></a>set集合</h2><p>集合是一个无序不重复元素的集。基本功能包括关系测试和消除重复元素。集合对象还支持 union（联合），intersection（交），difference（差）和 sysmmetric difference（对称差集）等数学运算。</p>
<pre>
def callset(basket):
    result= set(basket)
    print(result)

callset(basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'})
</pre>

<p>运行结果：</p>
<pre><code>{&#39;pear&#39;, &#39;orange&#39;, &#39;apple&#39;, &#39;banana&#39;}
</code></pre><h2 id="字典"><a href="#字典" class="headerlink" title="字典"></a>字典</h2><p>理解字典的最佳方式是把它看做无序的键：值对（key:value 对）集合，键必须是互不相同的（在同一个字典之内）。一对大括号创建一个空的字典： {} 。初始化列表时，在大括号内放置一组逗号分隔的键：值对，这也是字典输出的方式。</p>
<pre>
def calldict(dicts):
    print("原始字典",end=' ')
    print(dicts)   # 原始字典
    dicts['欧阳修'] = '宋朝' # 追加字典
    print("追加后的字典",end=' ')
    print(dicts)    # 追加后的字典
    print("字典键的集合",end=' ')
    print(list(dicts.keys())) # 字典键的集合
    print("字典键的排序",end=' ')
    print(sorted(dicts.keys())) # 字典键的排序
    print("字典值的集合",end=' ')
    print(list(dicts.values())) # 字典值的集合

calldict(dicts = {'李白': '唐朝', '杜甫': '唐朝'})
</pre>

<p>运行结果：</p>
<pre><code>原始字典 {&#39;杜甫&#39;: &#39;唐朝&#39;, &#39;李白&#39;: &#39;唐朝&#39;}
追加后的字典 {&#39;杜甫&#39;: &#39;唐朝&#39;, &#39;李白&#39;: &#39;唐朝&#39;, &#39;欧阳修&#39;: &#39;宋朝&#39;}
字典键的集合 [&#39;杜甫&#39;, &#39;李白&#39;, &#39;欧阳修&#39;]
字典键的排序 [&#39;李白&#39;, &#39;杜甫&#39;, &#39;欧阳修&#39;]
字典值的集合 [&#39;唐朝&#39;, &#39;唐朝&#39;, &#39;宋朝&#39;]
</code></pre><hr>
<h1 id="面向对象编程：类"><a href="#面向对象编程：类" class="headerlink" title="面向对象编程：类"></a>面向对象编程：类</h1><p>通过案例理解python中的类：父类是动物类，有初始化函数，且有动物讲话的方法，子类是一个狗类，继承父类所有属性，并扩展自己方法，调用子类讲话方法，并直接调用父类讲话方法。</p>
<pre>
"""
# 欢迎进入我的主页：http://www.cnblogs.com/baiboy/.
"""
class BaseAnimal: # 父类：动物
    def __init__(self,name,age): # 初始化方法：括号里是形参
        self.name=name
        self.age=age
    def speak(self): # 父类的行为方法
        print("我的名字是[ %s ],今年[ %d ]岁" %(self.name,self.age))


class SubDog(BaseAnimal): # 子类：小狗
    def __init__(self,name,age,say): # 初始化方法：括号里是形参
        BaseAnimal.__init__(self,name,age)
        self.say=say
        print("这是子类[ %s ]."%(self.name))
        print('_'*20+'调用子函数方法'+'_'*20)
    def talk(self):      # 子类的行为方法
        # BaseAnimal.speak(self) # 调用父类的行为方法
        print("我的名字是[ %s ],今年[ %d ]岁,我想说： %s" %(self.name,self.age,self.say))


ani=SubDog('dog',12,'汪汪...')
print(ani.talk())
print('_'*20+'直接调用父函数方法'+'_'*20)
BaseAnimal('tom',13).speak()
</pre>

<p>运行结果：</p>
<pre><code>这是子类[ dog ].

____________________调用子函数方法____________________

我的名字是[ dog ],今年[ 12 ]岁,我想说： 汪汪...

____________________直接调用父函数方法____________________

我的名字是[ tom ],今年[ 13 ]岁
</code></pre><p>解析： <strong> init </strong> 方法（双下划线）：<strong> init </strong> 方法在类的一个对象被建立时，马上运行。这个方法可以用来对你的对象初始化。<br>注意，这个名称的开始和结尾都是双下划线。我们把<strong>init</strong>方法定义为取一个参数name（以及普通的参数self）。在<strong> init </strong> 方法里，我们只是创建一个新的域，也称为name。注意:它们是两个不同的变量，尽管它们有相同的名字。点号使我们能够区分它们。最重要的是，在创建一个类的新实例的时候，把参数包括在圆括号内跟在类名后面，从而传递给 <strong> init </strong> 方法。这是这种方法的重要之处。现在，我们能够在我们的方法中使用self.name域。给C++/Java/C#程序员的注释 <strong> init </strong> 方法类似于C++、C#和Java中的constructor 。</p>
<hr>
<h1 id="标准库"><a href="#标准库" class="headerlink" title="标准库"></a>标准库</h1><p>Python拥有一个强大的标准库。Python语言的核心只包含数字、字符串、列表、字典、文件等常见类型和函数，而由Python标准库提供了系统管理、网络通信、文本处理、数据库接口、图形系统、XML处理等额外的功能。<br>Python标准库的主要功能有：</p>
<ol>
<li>文本处理，包含文本格式化、正则表达式匹配、文本差异计算与合并、Unicode支持，二进制数据处理等功能</li>
<li>文件处理，包含文件操作、创建临时文件、文件压缩与归档、操作配置文件等功能</li>
<li>操作系统功能，包含线程与进程支持、IO复用、日期与时间处理、调用系统函数、日志（logging）等功能</li>
<li>网络通信，包含网络套接字，SSL加密通信、异步网络通信等功能</li>
<li>网络协议，支持HTTP，FTP，SMTP，POP，IMAP，NNTP，XMLRPC等多种网络协议，并提供了编写网络服务器的框架</li>
<li>W3C格式支持，包含HTML，SGML，XML的处理。</li>
<li>其它功能，包括国际化支持、数学运算、HASH、Tkinter等</li>
</ol>
<p>Python社区提供了大量的第三方模块，使用方式与标准库类似。它们的功能覆盖科学计算、Web开发、数据库接口、图形系统多个领域。第三方模块可以使用Python或者C语言编写。SWIG,SIP常用于将C语言编写的程序库转化为Python模块。Boost C++ Libraries包含了一组库，Boost.Python，使得以Python或C++编写的程序能互相调用。Python常被用做其他语言与工具之间的“胶水”语言。</p>
<hr>
<h1 id="Python第三方库"><a href="#Python第三方库" class="headerlink" title="Python第三方库"></a>Python第三方库</h1><h2 id="Web框架库"><a href="#Web框架库" class="headerlink" title="Web框架库"></a>Web框架库</h2><ul>
<li>Django： 开源Web开发框架，它鼓励快速开发,并遵循MVC设计，开发周期短。</li>
<li>Flask：  轻量级的Web框架。</li>
<li>Pyramid： 轻量，同时有可以规模化的Web框架，Pylon projects 的一部分。</li>
<li>ActiveGrid： 企业级的Web2.0解决方案。</li>
<li>Karrigell： 简单的Web框架，自身包含了Web服务，py脚本引擎和纯python的数据库PyDBLite。</li>
<li>Tornado： 一个轻量级的Web框架，内置非阻塞式服务器，而且速度相当快</li>
<li>webpy： 一个小巧灵活的Web框架，虽然简单但是功能强大。</li>
<li>CherryPy： 基于Python的Web应用程序开发框架。</li>
<li>Pylons： 基于Python的一个极其高效和可靠的Web开发框架。</li>
<li>Zope： 开源的Web应用服务器。</li>
<li>TurboGears： 基于Python的MVC风格的Web应用程序框架。</li>
<li>Twisted： 流行的网络编程库，大型Web框架。</li>
<li>Quixote： Web开发框架。<h2 id="科学计算库"><a href="#科学计算库" class="headerlink" title="科学计算库"></a>科学计算库</h2></li>
<li>Matplotlib： 用Python实现的类matlab的第三方库，用以绘制一些高质量的数学二维图形。</li>
<li>Pandas： 用于数据分析、数据建模、数据可视化的第三方库。</li>
<li>SciPy： 基于Python的matlab实现，旨在实现matlab的所有功能。</li>
<li>NumPy： 基于Python的科学计算第三方库，提供了矩阵，线性代数，傅立叶变换等等的解决方案。<h2 id="GUI库"><a href="#GUI库" class="headerlink" title="GUI库"></a>GUI库</h2></li>
<li>PyGtk： 基于Python的GUI程序开发GTK+库。</li>
<li>PyQt： 用于Python的QT开发库。</li>
<li>WxPython： Python下的GUI编程框架，与MFC的架构相似。<h2 id="其他库"><a href="#其他库" class="headerlink" title="其他库"></a>其他库</h2></li>
<li>BeautifulSoup： 基于Python的HTML/XML解析器，简单易用。</li>
<li>gevent： python的一个高性能并发框架,使用了epoll事件监听、协程等机制将异步调用封装为同步调用。</li>
<li>PIL： 基于Python的图像处理库，功能强大，对图形文件的格式支持广泛。目前已无维护，另一个第三方库Pillow实现了对PIL库的支持和维护。</li>
<li>PyGame： 基于Python的多媒体开发和游戏软件开发模块。</li>
<li>Py2exe： 将python脚本转换为windows上可以独立运行的可执行程序。</li>
<li>Requests： 适合于人类使用的HTTP库，封装了许多繁琐的HTTP功能，极大地简化了HTTP请求所需要的代码量。</li>
<li>scikit-learn： 机器学习第三方库，实现许多知名的机器学习算法。</li>
<li>TensorFlow： Google开发维护的开源机器学习库。</li>
<li>Keras： 基于TensorFlow，Theano与CNTK的高级神经网络API。</li>
<li>SQLAlchemy： 关系型数据库的对象关系映射(ORM)工具</li>
</ul>
<hr>
<h1 id="参考文献"><a href="#参考文献" class="headerlink" title="参考文献"></a>参考文献</h1><ol>
<li><a href="https://www.python.org/downloads/" target="_blank" rel="noopener">Python官网</a></li>
<li><a href="https://zh.wikipedia.org/wiki/Python" target="_blank" rel="noopener">中文维基百科</a></li>
<li><a href="https://github.com/BaiNingchao/MachineLearning-1" target="_blank" rel="noopener">GitHub</a></li>
<li>图书：《机器学习实战》</li>
<li><a href="https://baike.baidu.com/item/%E8%87%AA%E7%84%B6%E8%AF%AD%E8%A8%80%E5%A4%84%E7%90%86%E7%90%86%E8%AE%BA%E4%B8%8E%E5%AE%9E%E6%88%98" target="_blank" rel="noopener">图书：《自然语言处理理论与实战》</a></li>
</ol>
<h1 id="完整代码下载"><a href="#完整代码下载" class="headerlink" title="完整代码下载"></a>完整代码下载</h1><blockquote>
<p>源码请进【机器学习和自然语言QQ群：436303759】文件下载：<a target="_blank" href="http://shang.qq.com/wpa/qunwpa?idkey=ef3bbb679b06ac59b136c57ba9e7935ff9d3b10faeabde6e4efcafe523bbbf4d"><img border="0" src="http://pub.idqqimg.com/wpa/images/group.png" alt="自然语言处理和机器学习技术QQ交流" title="自然语言处理和机器学习技术交流"></a></p>
</blockquote>
<h1 id="作者声明"><a href="#作者声明" class="headerlink" title="作者声明"></a>作者声明</h1><blockquote>
<p>本文版权归作者所有，旨在技术交流使用。未经作者同意禁止转载，转载后需在文章页面明显位置给出原文连接，否则相关责任自行承担。</p>
</blockquote>

      
    </div>

    

    
    
    

    
      <div>
        <div id="wechat_subscriber" style="display: block; padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/uploads/wechat.png" alt="白宁超 wechat" style="width: 200px; max-width: 100%;"/>
    <div>扫一扫关注微信公众号，机器学习和自然语言处理，订阅号datathinks！</div>
</div>

      </div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div></div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="白宁超 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="白宁超 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"><i class="fa fa-tag"></i> Python</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div class="social_share">
            
               <div>
                 
  <div class="bdsharebuttonbox">
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
    <a href="#" class="bds_douban" data-cmd="douban" title="分享到豆瓣网"></a>
    <a href="#" class="bds_sqq" data-cmd="sqq" title="分享到QQ好友"></a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a>
    <a href="#" class="bds_tieba" data-cmd="tieba" title="分享到百度贴吧"></a>
    <a href="#" class="bds_twi" data-cmd="twi" title="分享到Twitter"></a>
    <a href="#" class="bds_fbook" data-cmd="fbook" title="分享到Facebook"></a>
    <a href="#" class="bds_more" data-cmd="more"></a>
    <a class="bds_count" data-cmd="count"></a>
  </div>
  <script>
    window._bd_share_config = {
      "common": {
        "bdText": "",
        "bdMini": "2",
        "bdMiniList": false,
        "bdPic": ""
      },
      "share": {
        "bdSize": "16",
        "bdStyle": "0"
      },
      "image": {
        "viewList": ["tsina", "douban", "sqq", "qzone", "weixin", "twi", "fbook"],
        "viewText": "分享到：",
        "viewSize": "16"
      }
    }
  </script>

<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

               </div>
            
            
               <div id="needsharebutton-postbottom">
                 <span class="btn">
                    <i class="fa fa-share-alt" aria-hidden="true"></i>
                 </span>
               </div>
            
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/10/10/简明的Python教程之概述篇/" rel="next" title="简明的Python教程之概述篇">
                <i class="fa fa-chevron-left"></i> 简明的Python教程之概述篇
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/10/10/简明的Python教程之网站篇/" rel="prev" title="简明的Python教程之网站篇">
                简明的Python教程之网站篇 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zOTc5NC8xNjMyMQ=="></div>
    </div>

  
 





        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/../images/header.png"
                alt="白宁超" />
            
              <p class="site-author-name" itemprop="name">白宁超</p>
              <p class="site-description motion-element" itemprop="description">本站主要研究深度学习、机器学习、自然语言处理等前沿技术。ML&NLP交流群：436303759 <span><a target="_blank" href="http://shang.qq.com/wpa/qunwpa?idkey=ef3bbb679b06ac59b136c57ba9e7935ff9d3b10faeabde6e4efcafe523bbbf4d"><img border="0" src="http://pub.idqqimg.com/wpa/images/group.png" alt="自然语言处理和机器学习技术QQ交流：436303759 " title="自然语言处理和机器学习技术交流"></a></span></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives">
                
                    <span class="site-state-item-count">65</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">29</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">119</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/bainingchao" target="_blank" title="GitHub" rel="external nofollow"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.google.com.hk/" target="_blank" title="Google" rel="external nofollow"><i class="fa fa-fw fa-google"></i>Google</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.baidu.com/" target="_blank" title="百度" rel="external nofollow"><i class="fa fa-fw fa-globe"></i>百度</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://weibo.com/p/1005056002073632?is_all=1" target="_blank" title="微博" rel="external nofollow"><i class="fa fa-fw fa-weibo"></i>微博</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="http://www.cnblogs.com/baiboy/" target="_blank" title="博客园" rel="external nofollow"><i class="fa fa-fw fa-globe"></i>博客园</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://mp.weixin.qq.com/s/s97I4gtEJIt5rMivWMkPkQ" target="_blank" title="微信公众号" rel="external nofollow"><i class="fa fa-fw fa-weixin"></i>微信公众号</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#语句和控制流"><span class="nav-number">1.</span> <span class="nav-text">语句和控制流</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Hello-World"><span class="nav-number">1.1.</span> <span class="nav-text">Hello World</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#if-语句-根据成绩评判等级"><span class="nav-number">1.2.</span> <span class="nav-text">if 语句::根据成绩评判等级</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#列表的切分"><span class="nav-number">1.3.</span> <span class="nav-text">列表的切分</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#List-列表作堆栈-先进先出"><span class="nav-number">1.4.</span> <span class="nav-text">List :列表作堆栈(先进先出)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#List-列表作队列-先进后出"><span class="nav-number">1.5.</span> <span class="nav-text">List :列表作队列(先进后出)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#列表推导式"><span class="nav-number">1.6.</span> <span class="nav-text">列表推导式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#列表的矩阵转秩"><span class="nav-number">1.7.</span> <span class="nav-text">列表的矩阵转秩</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#元组-集合-字典"><span class="nav-number">2.</span> <span class="nav-text">元组/集合/字典</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#操作元组"><span class="nav-number">2.1.</span> <span class="nav-text">操作元组</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#set集合"><span class="nav-number">2.2.</span> <span class="nav-text">set集合</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#字典"><span class="nav-number">2.3.</span> <span class="nav-text">字典</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#面向对象编程：类"><span class="nav-number">3.</span> <span class="nav-text">面向对象编程：类</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#标准库"><span class="nav-number">4.</span> <span class="nav-text">标准库</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Python第三方库"><span class="nav-number">5.</span> <span class="nav-text">Python第三方库</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Web框架库"><span class="nav-number">5.1.</span> <span class="nav-text">Web框架库</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#科学计算库"><span class="nav-number">5.2.</span> <span class="nav-text">科学计算库</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#GUI库"><span class="nav-number">5.3.</span> <span class="nav-text">GUI库</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#其他库"><span class="nav-number">5.4.</span> <span class="nav-text">其他库</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#参考文献"><span class="nav-number">6.</span> <span class="nav-text">参考文献</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#完整代码下载"><span class="nav-number">7.</span> <span class="nav-text">完整代码下载</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#作者声明"><span class="nav-number">8.</span> <span class="nav-text">作者声明</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
</script>

<div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">白宁超</span>

  

  
</div>




  



  <!--<div class="powered-by">由 <a class="theme-link" target="_blank" rel="external nofollow" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div> -->



   <!--<span class="post-meta-divider">|</span>-->



   <!--<div class="theme-info">主题 – <a class="theme-link" target="_blank" rel="external nofollow" href="https://theme-next.org">NexT.Gemini</a> v6.4.1</div>-->




        <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



<div class="busuanzi-count">
  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
	
    

    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.4.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.4.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.1"></script>



  



  
    <script type="text/javascript">
      window.livereOptions = {
        refer: '2018/10/10/简明的Python教程之实例篇/'
      };
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  










  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  

  
    
      <script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      },
      TeX: {equationNumbers: { autoNumber: "AMS" }}
    });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>
<script type="text/javascript" src="//cdn.jsdelivr.net/npm/mathjax@2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>

    
  


  
  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "box";
      
          pbOptions.boxForm = "horizontal";
      
          pbOptions.position = "bottomCenter";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Linkedin,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
  </script>

  

  

  

  

  

  

  <!-- 页面点击小红心 -->
	<script type="text/javascript" src="../js/src/love.js"></script><!-- hexo-inject:begin --><!-- Begin: Injected MathJax -->
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({"tex2jax":{"inlineMath":[["$","$"],["\\(","\\)"]],"skipTags":["script","noscript","style","textarea","pre","code"],"processEscapes":true},"TeX":{"equationNumbers":{"autoNumber":"AMS"}}});
</script>

<script type="text/x-mathjax-config">
  MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
      all[i].SourceElement().parentNode.className += ' has-jax';
    }
  });
</script>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js">
</script>
<!-- End: Injected MathJax -->
<!-- hexo-inject:end -->
</body>
</html>
